<?php  defined('SYSPATH') OR die('No direct access allowed.');

/**
 *质检入库的类方法
 * @package  qcwo
 * @author   taj
 */
class  qcwo
{
    /**
     *查询质检详情数据
     * @static
     * @param int $reo  质检详情单号
     * @param int $type 入库类型10采购正常入库；20特殊入库；30订单退回入库；
     * @return array $res array(0=>array()) 入库详情数据
     */
    public static function selectreo($reo,$type)
    {

        $cqd = ORM::factory('check_quality_detail',$reo);
        if($cqd->id==''){
            $info = $reo.'，这个质检详情单号系统中没有';
            return $info;
        }else{
            $sel_qc = "SELECT cqd.id as check_quality_detail_id,cqd.sku,cqd.sku_name,cqd.sku_standard,
cqd.storage_position,cqd.qualified_quantity as quantity,cqd.purchaseorder_id,cqd.supplier_id,cqd.store,cqd.batch_code,cqd.warehouseid
FROM check_quality_details cqd where cqd.id='".$reo."'";
            $res    = DB::query(Database::SELECT,$sel_qc)
                ->execute('newerp')
                ->as_array();

            foreach($res as &$re){
                $re['warehouse_man'] = User::active_user()->id;
                $re['type']          = $type;
                if($type==10){
                    $re['remark'] = '采购入库';
                }

                //查找采购详情单，算采购金额和成本
                $pod = ORM::factory('purchaseorder_detail')
                    ->where('purchaseorder_id','=',$re['purchaseorder_id'])
                    ->where('sku','=',$re['sku'])
                    ->find();
                /*if($pod->tax_way==0){//不计税时，成本=金额；税额=0
                    $re['single_price'] = $pod->single_price;
                    $re['money'] =$pod->single_price*$re['quantity'];
                    $re['cost'] = $re['money'];
                    $re['tax_price'] = 0;
                }else if($pod->tax_way==-1){//加内税的计算成本和税额
                    $re['single_price'] = $pod->single_price;
                    $re['money'] =$pod->single_price*$re['quantity'];
                    $re['cost'] = ($pod->single_price*$re['quantity'])/(1+$pod->tax_rate);
                    $re['tax_price'] = ($pod->single_price*$re['quantity'])/(1+$pod->tax_rate)*$pod->tax_rate;

                }else if($pod->tax_way==1){//加外税时的计算成本和税额
                    $re['single_price'] = $pod->single_price;
                    $re['money'] =($pod->single_price*$re['quantity'])*(1+$pod->tax_rate);
                    $re['cost'] = $pod->single_price*$re['quantity'];
                    $re['tax_price'] = ($pod->single_price*$re['quantity'])*$pod->tax_rate;

                }*/
                //$re['sku_unit'] = $pod->sku_unit;

                $sku_price          = new Service_Common();
                $price              = $sku_price->get_sku_money_cost(
                                            $pod->single_price,$re['quantity'],$pod->tax_way,$pod->tax_rate
                                                );
                $re['single_price'] = $price['single_price'];
                $re['money']        = $price['money'];
                $re['cost']         = $price['cost'];
                $re['tax_price']    = $price['tax_price'];
            }

            return $res;
        }
    }

    /**
     *在入库单表中插入入库记录
     * @param array $wos 质检合格的入库详细数据
     * @return string $info 入库单插入成功与否的反馈
     */
    public static function insert_wo($wos)
    {
        
        if(is_array($wos)){ //合格质检单入库
            foreach($wos as $wo){
                $warehouse_id = $wo['warehouseid'];
                $sql='SELECT `export_tax_rebate` FROM `purchaseorders`
                      WHERE `id`='.$wo['purchaseorder_id'];
                $export_sign=DB::query(Database::SELECT,$sql)->execute('newerp')->get('export_tax_rebate');
                $insert_wo = ORM::factory('warehouseorder');

                //求采购物品的运费
                $purchaseorder_details             = ORM::factory('purchaseorder_detail')
                    ->where('purchaseorder_id','=',$wo['purchaseorder_id'])
                    ->where('sku','=',$wo['sku'])
                    ->find();
                $single_transportation_expense =
                    $purchaseorder_details->transportation_expense/$purchaseorder_details->quantity;
                $insert_wo->transportation_expense = $single_transportation_expense*$wo['quantity']; //插入运费
                if($export_sign==1){
                    $sql='SELECT `real_tax_rate` FROM `purchaseorder_details`
                      WHERE `purchaseorder_id`='.$wo['purchaseorder_id']
                        .' AND `sku`="'.$wo['sku'].'"';
                    $real_tax_rate=DB::query(Database::SELECT,$sql)->execute('newerp')->get('real_tax_rate');
                    $insert_wo->purchaseorders_id       = $wo['purchaseorder_id'];
                    $insert_wo->check_quality_detail_id = $wo['check_quality_detail_id'];
                    $insert_wo->warehouseid             = $warehouse_id;
                    $insert_wo->supplier_id             = $wo['supplier_id'];
                    $insert_wo->sku                     = $wo['sku'];
                    $insert_wo->sku_name                = $wo['sku_name'];
                    $insert_wo->sku_standard            = $wo['sku_standard'];
                    $insert_wo->warehouse_quantity      = $wo['quantity'];
                    $insert_wo->single_price            = $wo['single_price']*(1+$real_tax_rate)/1.17;
                    $insert_wo->money                   = $wo['money']*(1+$real_tax_rate)/1.17;
                    $insert_wo->batch_code              =$wo['batch_code'];
                    $insert_wo->cost                   = $wo['cost']*(1+$real_tax_rate)/1.17+$insert_wo->transportation_expense; //成本=采购成本+运费
                }else{
                    $insert_wo->purchaseorders_id       = $wo['purchaseorder_id'];
                    $insert_wo->check_quality_detail_id = $wo['check_quality_detail_id'];
                    $insert_wo->warehouseid             = $warehouse_id;
                    $insert_wo->supplier_id             = $wo['supplier_id'];
                    $insert_wo->sku                     = $wo['sku'];
                    $insert_wo->sku_name                = $wo['sku_name'];
                    $insert_wo->sku_standard            = $wo['sku_standard'];
                    
                    $insert_wo->warehouse_quantity      = $wo['quantity'];
                    $insert_wo->single_price            = $wo['single_price'];
                    $insert_wo->money                   = $wo['money'];
                    $insert_wo->batch_code              =$wo['batch_code'];
                    $insert_wo->cost                   = $wo['cost']+$insert_wo->transportation_expense; //成本=采购成本+运费
                }
                $insert_wo->storage_position        = Skusystemapi::getSkuPlacesForVMI($insert_wo->sku, $warehouse_id);
                if(empty($insert_wo->storage_position)){
                    return 7;
                }
                $insert_wo->tax_way        = $purchaseorder_details->tax_way;
                $insert_wo->tax_price      = $wo['tax_price'];
                $insert_wo->remark         = $wo['remark'];
                $insert_wo->type           = $wo['type'];
                $insert_wo->warehouse_man  = $wo['warehouse_man'];
                $insert_wo->op_time        = date('Y-m-d H:i:s',time());
                $insert_wo->warehouse_date = date('Y-m-d H:i:s',time());
                $insert_wo->store          = $wo['store'];

                //获取采购单的主体、转运仓、运输方式、退税类型
                $purchaseorders             = ORM::factory('purchaseorders')
                    ->where('id','=',$wo['purchaseorder_id'])
                    ->find();
                $insert_wo->store      = !empty($purchaseorders->store)?$purchaseorders->store:0;
                $insert_wo->enterprise_dominant      = $purchaseorders->enterprise_dominant;
                $insert_wo->export_tax_rebate      = $purchaseorders->export_tax_rebate;
                $insert_wo->transfer_hopper_id      = $purchaseorders->transfer_hopper_id;
                $insert_wo->transfer_type      = $purchaseorders->transfer_type;


                $insert_wo->save();
                if($insert_wo->saved()){
                    $notice  = qcwo::inventory_notice($wos);
                    $arr_wo  = qcwo::select_po_wo($wo['purchaseorder_id'],$wo['sku'],$wo['quantity']);
                    $notice2 = purchase::update_po($arr_wo); //采购单回写状态
                    if($notice=='ok'&&$notice2=='ok'){
                        if(!empty($insert_wo->storage_position) && in_array($insert_wo->storage_position, array('YDCW0001'))) {
                            $wareOrdId = DB::select('id')->from('warehouseorders')
                                ->where('purchaseorders_id', '=', $insert_wo->purchaseorders_id)
                                ->and_where('warehouse_date', '=', $insert_wo->warehouse_date)
                                ->and_where('sku', '=', $insert_wo->sku)
                                ->and_where('warehouse_quantity', '=', $insert_wo->warehouse_quantity)
                                ->execute('newerp')
                                ->get('id');

                            $pushData = array();
                            $pushData['wms_co_id'] = intval($warehouse_id);
                            $pushData['io_id'] = $wareOrdId;
                            $pushData['io_date'] = $insert_wo->warehouse_date;
                            $pushData['items'][] = array(
                                'io_id' => $wareOrdId,
                                'ioi_id'=> $wareOrdId,
                                'sku_id'=> $insert_wo->sku,
                                'qty' => $insert_wo->warehouse_quantity,
                                'name' => $insert_wo->sku_name
                            );

                            $re = stwmsapi::prePush($pushData);
                            //增加日志
                            /*DB::insert('stwmsapi_log')
                                ->columns(array('info', 'msg'))
                                ->values(array(json_encode($pushData), json_encode($re)))
                                ->execute('newerp');*/
                            if(!isset($re['state']) || $re['state'] != 200) {
                                $info = '推送智能仓库失败:' . $re['info'];
                            }
                        }

                        empty($info) && $info = 'ok';
                    }else{
                        $info = '入库记录插入库存成本表失败或采购单回写状态';
                    }
                }else{

                    $info = '系统中入库记录插入失败';
                }
            }
        }else{ //不合格质检单折让入库,此时$wos是一个不合格产品处理的ID
            $unqualified_deal_invoices = ORM::factory('unqualified_deal_invoice',$wos);

            if($unqualified_deal_invoices->id==''){
                $info = $wos.'这个不合格质检详情单号在系统中不存在';
            }elseif($unqualified_deal_invoices->status==30){
                if($unqualified_deal_invoices->fail_deal_way==5){
                    $warehouseorders                 = ORM::factory('warehouseorder');
                    $warehouseorders->warehouse_date = date('Y-m-d H:i:s');
                    //$warehouseorders->unqualified_deal_invoice_id=
                    $warehouseorders->purchaseorders_id           = $unqualified_deal_invoices->purchaseorder_id;
                    $warehouseorders->unqualified_deal_invoice_id = $unqualified_deal_invoices->id;
                    $warehouseorders->supplier_id                 = $unqualified_deal_invoices->supplier;
                    $warehouseorders->sku                         = $unqualified_deal_invoices->sku;
                    $warehouseorders->sku_name                    = $unqualified_deal_invoices->sku_name;
                    $warehouseorders->sku_standard                = $unqualified_deal_invoices->sku_standard;

                    $check_quality_details = ORM::factory(
                                            'check_quality_detail',$unqualified_deal_invoices->check_detail_id
                                                );
                    $warehouseorders->storage_position = $check_quality_details->storage_position;

                    $warehouseorders->warehouse_quantity     = $unqualified_deal_invoices->quantity;
                    $warehouseorders->single_price           = $unqualified_deal_invoices->coupon_price;
                    $warehouseorders->money = $unqualified_deal_invoices->quantity
                                            *$unqualified_deal_invoices->coupon_price;
                    $warehouseorders->tax_price              = 0;
                    $warehouseorders->cost = $warehouseorders->money
                                            +$unqualified_deal_invoices->return_cost; //成本要包含运费
                    $warehouseorders->remark                 = '采购折让入库';
                    $warehouseorders->transportation_expense = $unqualified_deal_invoices->return_cost;
                    $warehouseorders->type                   = 10;
                    $warehouseorders->warehouse_man          = User::active_user()->id;
                    $warehouseorders->store                  = $unqualified_deal_invoices->store;
                    $warehouseorders->warehouseid            = $warehouse_id;
                    $warehouseorders->save();
                    if($warehouseorders->saved()){
                        $notice  = qcwo::inventory_notice($wos);
                        $arr_wo  = qcwo::select_po_wo($unqualified_deal_invoices->purchaseorder_id,
                                                        $unqualified_deal_invoices->sku,
                                                        $unqualified_deal_invoices->quantity);
                        $notice2 = purchase::update_po($arr_wo); //采购单回写状态

                        if($notice=='ok'&&$notice2=='ok'){
                            $info = 'ok';
                        }else{
                            $info = '入库记录插入库存成本表失败或采购单回写状态';
                        }
                    }else{
                        $info = $wos.'系统中插入入库记录失败';
                    }
                }else{

                    $info = $wos.'此不合格处理单号采购员已确认，不可以折让入库';
                }
            }else{
                $info = $wos.'此不合格质检单号采购员还没确认，不可以入库';
            }
        }
        return $info;
    }

    /**
     *通过质检详情单号在入库单表中查询入库记录
     * @param int $cqd_id 质检详情单号
     * @param int $notice 判断是合格的质检详情单号，代表是0；还是不合格的质检详情单号，用1代表；
     * @return object  入库单是否存在此质检单号的记录信息
     */

    public static function select_wo($cqd_id,$notice = NULL)
    {
        if($notice==1){
            $select_wo = ORM::factory('warehouseorder')
                ->where('unqualified_deal_invoice_id','=',$cqd_id)
                ->find();
            return $select_wo;
        }else{
            $select_wo = ORM::factory('warehouseorder')
                ->where('check_quality_detail_id','=',$cqd_id)
                ->find();
            return $select_wo;
        }
    }

    /**
     *通过质检详情单号在库存表中查询此sku的记录
     * @param array $wos 需入库的质检详情数据
     * @return string 插入是否成功的反馈
     */
    public static function inventory_notice($wos)
    {
        $warehouse_id = Kohana::$config->get('warehouse')->warehouse_id;
        if(is_array($wos)){
            foreach($wos as $wo){
                $date      = date('Y-m',time());
                $date1     = $date.'-01';
                $inventory = ORM::factory('inventory')
                    ->where('sku','=',$wo['sku'])
                    ->where('inventory_date','=',$date.'-01')
                    ->find();
                if($inventory->id!=''){
                    return 'ok';
                    continue;
                }
                $inventory_in                   = ORM::factory('inventory');
                $inventory_in->inventory_date   = $date1;
                $inventory_in->sku              = $wo['sku'];
                $inventory_in->sku_name         = $wo['sku_name'];
                $inventory_in->sku_standard     = $wo['sku_standard'];
                $inventory_in->storage_position = $wo['storage_position'];
                $inventory_in->supplier_id      = $wo['supplier_id'];
                $inventory_in->quantity         = 0;
                $inventory_in->cost             = 0;
                $inventory_in->warehouseid      = $warehouse_id;
                $inventory_in->save();
                if($inventory_in->saved()){
                    return 'ok';
                }else{
                    return 'no';
                }
            }
        }else{
            $date      = date('Y-m',time());
            $date1     = $date.'-01';
            $udi       = ORM::factory('unqualified_deal_invoice',$wos);
            $inventory = ORM::factory('inventory')
                ->where('sku','=',$udi->sku)
                ->where('inventory_date','=',$date.'-01')
                ->find();
            if($inventory->id!=''){
                return 'ok';
            }

            $inventory_in                 = ORM::factory('inventory');
            $inventory_in->inventory_date = $date1;
            $inventory_in->sku            = $udi->sku;
            $inventory_in->sku_name       = $udi->sku_name;
            $inventory_in->sku_standard   = $udi->sku_standard;

            $check_quality_details          = ORM::factory('check_quality_detail',$udi->check_detail_id);
            $inventory_in->storage_position = $check_quality_details->storage_position;

            $inventory_in->supplier_id  = $udi->supplier;
            $inventory_in->quantity     = 0;
            $inventory_in->cost         = 0;
            $inventory_in->warehouse_id = $warehouse_id;
            $inventory_in->save();
            if($inventory_in->saved()){
                return 'ok';
            }else{

                return 'no';
            }
        }
    }

    /**
     *通过质检详情单号在入库单表中查询入库记录
     * @param int    $poid 采购单id
     * @param string $sku  产品sku
     * @return array $arr
     */
    public static function select_po_wo($poid,$sku,$now_num = NULL)
    {

        $arr         = array();
        $arr['poid'] = $poid;
        $arr['sku']  = $sku;
        if($now_num){
            $num = $now_num;
        }else{
            $num = 0;
        }
        /*$sel_wo = "SELECT sum(warehouse_quantity) as num FROM warehouseorders WHERE purchaseorders_id='".$poid."'
                        AND sku='".$sku."'";
        $wo_num = DB::query(Database::SELECT,$sel_wo)->execute('newerp')->as_array();

        if(isset($wo_num[0]['num']) && !empty($wo_num[0]['num'])){
            $arr['num'] = $wo_num[0]['num'];
        }else{
            $arr['num'] = 0;
        }*/

        $pd         = ORM::factory('purchaseorder_detail')
            ->where('purchaseorder_id','=',$poid)
            ->where('sku','=',$sku)
            ->find();
        $arr['num'] = intval($pd->ware_quantity)+$num;
        return $arr;
    }
    /**nirui!!!
     * 每次入库更新进销存成本价表 newerp_sku_cost
     */
    public static function updatesystemskucosts($checkDetailIds){
        if(!empty($checkDetailIds)) {
            $wareDetails = DB::select('id', 'sku', 'check_quality_detail_id', 'warehouse_quantity',
                                    'single_price', 'transportation_expense' )
                            ->from('warehouseorders')
                            ->where('check_quality_detail_id', 'IN', array_keys($checkDetailIds))
                            ->execute('newerp')
                            ->as_array();
            foreach ($wareDetails as $wareDetail) {
                $oriPrice = DB::select('id', 'cost')
                    ->from('newerp_sku_cost')
                    ->where('sku', '=', $wareDetail['sku'])
                    ->execute('newerp_hz')
                    ->current();
                $basequantity=self::getHzStock($wareDetail['sku'],$wareDetail['id']);
                if(empty($oriPrice)) {

                } else {
                    $newskucost=($oriPrice['cost']*$basequantity[$wareDetail['sku']]
                            +$wareDetail['warehouse_quantity']*$wareDetail['single_price']
                            +$wareDetail['transportation_expense'])
                            /$basequantity[$wareDetail['sku']];
                    $sql = 'UPDATE `newerp_sku_cost` SET `cost` = ' . $newskucost . ' WHERE `id` = ' . $oriPrice['id'];
                    DB::query(Database::UPDATE,$sql)->execute('newerp_hz');
                }

            }
        }
    }

    static function getHzStock($skus = NULL,$newarehouseid)
    {
        if(empty($skus)) return array();
        if($skus){
            $skus_string = "";
            if(is_array($skus)){

                foreach($skus as $sku){
                    $skus_string .= $skus_string?",'".$sku."'":"'".$sku."'";
                }
            }else{
                $skus_string="'".$skus."'";
            }

            $date = date('Y-m-d');;
            $sql_string = "select upper(sku) as sku,sum(num) as inventory from (
                                SELECT
                                    `inventories`.`sku` AS `sku`,
                                    `inventories`.`quantity` AS `num`
                                FROM
                                    `inventories`
                                WHERE
                                    `inventories`.`inventory_date` = DATE_FORMAT('".$date."', '%Y-%m-01')
                                AND sku in (".$skus_string.")
                                UNION ALL
                                SELECT
                                    `deliveryorders`.`sku` AS `sku` ,- (
                                        `deliveryorders`.`quantity`
                                    ) AS `num`
                                FROM
                                   `deliveryorders`
                                WHERE
                                   `deliveryorders`.`delivery_date` >= DATE_FORMAT('".$date."', '%Y-%m-01')
                                AND sku in (".$skus_string.")
                                UNION ALL
                                SELECT
                                    warehouseorders.sku AS sku,
                                    warehouseorders.warehouse_quantity AS num
                                FROM
                                    warehouseorders
                                WHERE
                                    warehouseorders.warehouse_date >= DATE_FORMAT('".$date."', '%Y-%m-01')
                                AND sku in (".$skus_string.")
                                AND id != ".$newarehouseid."
                             ) a GROUP BY sku";

            $re = DB::query(Database::SELECT,$sql_string)
                ->execute('newerp_hz')
                ->as_array('sku');

            $inventory = array();
            if($re){
                foreach($re as $value){
                    if(!empty($value['sku']))
                        $inventory[trim($value['sku'])] = $value['inventory'];
                }
            }

            return $inventory;
        }
    }

}